
// import { WebGLRenderer, Scene, PerspectiveCamera, Vector3, MOUSE, Vector2, Raycaster } from 'three' //用到的太多dev使用全局，优化时使用按需
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { TransformControls } from 'three/examples/jsm/controls/TransformControls'
export const renderer = new THREE.WebGLRenderer()  // 创建渲染器 
export const scene = new THREE.Scene()  // 实例化场景
const mouse = new THREE.Vector2() // 初始化鼠标位置
const raycaster = new THREE.Raycaster()//初始化射线发射器
export const clock = new THREE.Clock();
const loader = new GLTFLoader()
export const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000)
export let mixer = null
//  屏幕鼠标x，屏幕鼠标y  视图宽度，视图高度
let x = 0; let y = 0; let width = 0; let height = 0
export class ThreeController {
  Model = null;
  scene = null;
  constructor(Model) {
    Model.appendChild(renderer.domElement)
    renderer.setSize(Model.offsetWidth, Model.offsetHeight, true)
    this.Model = Model
    // scene.background = SceneMapMaterial();
    this.scene = scene
    EventInjection(camera)
    camera.position.set(100, 100, 100) // 设置相机位置
    camera.lookAt(new THREE.Vector3(0, 0, 0))  // 设置相机看先中心点
    camera.up = new THREE.Vector3(0, 1, 0)  // 设置相机自身的方向
    renderer.shadowMap.enabled = true;
    animate()
    }
    addObject(...object) {
      object.forEach(elem => {
        this.scene.add(elem)
      })
    }
}
// Loading gltf
export const LoadingGLTFMethod=(GltfModel,type)=> {
  loader.load(`${process.env.BASE_URL}model/${GltfModel}`, (gltf) => {
    gltf.scene.scale.set(15, 15, 15)
    gltf.scene.position.set(0, 0, 0)
    gltf.scene.userData={
      name:"LoadingGLTFModel",
      data:"123",
      id:"1212121212",
      title:"人物模型"
    }
    let axis = new THREE.Vector3(0, 1, 0);//向量axis
    gltf.scene.rotateOnAxis(axis, Math.PI);
    gltf.scene.traverse(function (object) {
      if (object.isMesh) {
        object.castShadow = true; //阴影
        object.receiveShadow = true; //接受别人投的阴影
      }
    })
    mixer = startAnimation(
      gltf.scene,
      gltf.animations,
      gltf.animations[type].name // animationName，1 是"Run"
    );
    scene.Model = gltf.scene;
    scene.add(gltf.scene) //公用访问时使用常量向场景中添加引入的模型
    return  gltf.scene
  })
}
// 动画
export const animate = () => {  
  requestAnimationFrame(animate);
  if (mixer) {
    mixer.update(clock.getDelta());
  }
  // rotate(camera,0.01,0.01,0.01);
  renderer.render(scene, camera);
}
// export const SceneMapMaterial=(urlList)=>{
export const SceneMapMaterial=(list)=>{
   const map=new THREE.CubeTextureLoader()
  .setPath( `${process.env.BASE_URL}model/` )
  .load(list );
   return map
}
// 事件注入
export function EventInjection(camera) {
  // 鼠标移动事件
  const transformControls = new TransformControls(camera, renderer.domElement)
  renderer.domElement.addEventListener("mousemove", event => {
    x = event.offsetX
    y = event.offsetY
    width = renderer.domElement.offsetWidth
    height = renderer.domElement.offsetHeight
    mouse.x = x / width * 2 - 1
    mouse.y = -y * 2 / height + 1
  })
  let transing = false
  transformControls.addEventListener("mouseDown", event => {
    transing = true
    return event
  })
  // 鼠标点击事件
  renderer.domElement.addEventListener("click", event => {
    if (transing) {
      transing = false
      return
    }
    scene.remove(transformControls) // 移除变换控制器
    transformControls.enabled = false // 停用变换控制器
    raycaster.setFromCamera(mouse, camera)  // 配置射线发射器，传递鼠标和相机对象
    const intersection = raycaster.intersectObjects(scene.children) // 获取射线发射器捕获的模型列表，传进去场景中所以模型，穿透的会返回我们
    if (intersection.length) {
      const object = intersection[0].object  // 获取第一个模型
      scene.add(transformControls) // 添加变换控制器
      transformControls.enabled = true // 启用变换控制器
      transformControls.attach(object)
    }
    return event
  })
  // 监听变换控制器模式更改
  document.addEventListener("keyup", event => {
    if (transformControls.enabled) {  // 变换控制器为启用状态执行
      if (event.key === 'e') { // 鼠标按下e键，模式改为缩放
        transformControls.mode = 'scale'
        return false
      }
      if (event.key === 'r') { // 鼠标按下r键，模式改为旋转
        transformControls.mode = 'rotate'
        return false
      }
      if (event.key === 't') { // 鼠标按下t键，模式改为平移
        transformControls.mode = 'translate'
        return false
      }
    }
    return event
  })
  // three.js自带的方法
  const orbitControls = new OrbitControls(camera, renderer.domElement)
  // console.log(MOUSE)//查看MOUSE中的配置项
  orbitControls.mouseButtons = {  // 设置鼠标功能键（轨道控制器）
    LEFT: null,  // 左键无事件
    MIDDLE: THREE.MOUSE.DOLLY,  // 中键缩放
    RIGHT: THREE.MOUSE.ROTATE// 右键旋转
  }
  scene.add(transformControls)
}
export function startAnimation(skinnedMesh, animations, animationName) {
  const m_mixer = new THREE.AnimationMixer(skinnedMesh);
  const clip = THREE.AnimationClip.findByName(animations, animationName);
  if (clip) {
    const action = m_mixer.clipAction(clip);
    action.play();
  }

  return m_mixer;
}







